//
//  SSNetwrokManager.swift
//  拾舍清洁
//
//  Created by sky.wei on 2023/5/2.
//

import UIKit

import Alamofire
import SwiftyJSON
import HandyJSON


class SSNetwrokManager: NSObject {
    
    var sessionManager = Session.init()
    
    static let share: SSNetwrokManager = {
        let tools = SSNetwrokManager()
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 30
        tools.sessionManager = Session.init(configuration: config)
        return tools
    }()
}

extension SSNetwrokManager
{
    func request(urlString: String,
                 parameters: [String:AnyObject] = [:],
                 isLoading:Bool = true,
                 isAlert:Bool = true,
                 finished: @escaping (_ result: String?) -> Void){
        
        let resultCallBack = {(response:AFDataResponse<String>) in
            SSProgressHUD.share.dismiss()
            switch response.result{
            case .success(_):
                var decryptStr = ""
                let responseStr = NSString.init(data: response.data ?? Data(), encoding: String.Encoding.utf8.rawValue) ?? ""
                decryptStr = responseStr as String
                let json = JSON(parseJSON: decryptStr)
                let retCode = json["retCode"].stringValue
                let retMsg = json["retMsg"].stringValue
                debugPrint("url       = \(urlString)")
                debugPrint("param     =",jhToJson(parameters))
                debugPrint("response  =",json)
                if(retCode == "0000"){
                    finished(decryptStr)
                }else{
                    if(isAlert) {dissmissToTast(msg: "\(retMsg)")}
                }
                
            case.failure(let error):
                debugPrint("connection error = \(error.localizedDescription)")
                let err = NSError.init(domain: "error", code: -10001, userInfo: ["errorinfo":"网络连接失败"])
                self.noNetworking()
                break
            }
        }
        
        let token = kUserToken
        var headers: HTTPHeaders = []
        let idfv:String = UIDevice.current.identifierForVendor?.uuidString ?? ""
        print("---token:\(token)")
        if(kIsLogin){
            headers = [
                "Content-Type":"application/json",
                "token":token,
                "idfv":idfv
            ]
        }else{
            headers = [
                "Content-Type":"application/json",
                "idfv":idfv
            ]
        }
        let data = try? JSONSerialization.data(withJSONObject: parameters , options: [])
        var request = try? URLRequest(url: URL(string: urlString)!, method: .post, headers: headers)
        request?.httpBody = data
        if(isLoading){SSProgressHUD.share.show()}
//        let config = URLSessionConfiguration.default
//        config.timeoutIntervalForRequest = 30
//        sessionManager = Session.init(configuration: config)
        sessionManager.request(request!).responseString(completionHandler: resultCallBack)
    }
    
    //第一次装app无气泡提示
    func noNetworking() {
        let key = kUserDefaults.value(forKey: kNetworking) as? String ?? ""
        if(key.count > 0){
            dissmissToTast(msg: "网络连接失败")
        }else{
            kUserDefaults.setValue("网络连接失败", forKey: kNetworking)
        }
    }

}


